import {
  Outlet,
  Link,
  useNavigate,
  useParams,
  RouterProvider,
  createBrowserRouter,
} from "react-router-dom";
import { IMAGES, getImageById } from "./images";
import { Modal, Spin } from "antd";
import { useMount } from "react-use";
import { useState } from "react";

export default function App() {
  return (
    <RouterProvider
      router={createBrowserRouter([
        {
          path: "/",
          element: <Root />,
          children: [
            {
              path: "/",
              element: <Post />,
              children: [
                {
                  path: "post/:id",
                  element: <Detail />,
                },
              ],
            },
          ],
        },
      ])}
    />
  );
}

export function Root() {
  return (
    <div className="container mx-auto p-10">
      <div className="text-2xl mb-2 text-center">Outlet Modal Example</div>
      <hr />
      <div className="px-40 py-10">
        <Outlet />
      </div>
    </div>
  );
}

export function Home() {
  return (
    <div>
      <p>
        Click over to the{" "}
        <Link to="/post" className="text-amber-600 font-bold">
          Gallery
        </Link>{" "}
        route to see the modal in action
      </p>
      <Outlet />
    </div>
  );
}

export function Post() {
  const [image, setImage] = useState<any[]>([]);
  useMount(() => {
    setTimeout(() => {
      setImage(IMAGES);
      console.log("加载图像");
    }, 1000);
  });
  return (
    <div className="flex flex-col">
      <Spin spinning={image.length === 0}>
        {image.map((i) => (
          <Link key={i.id} to={`post/${i.id}#ww`} state={{ modal: true }}>
            <img className="w-full" src={i.src} alt={i.title} />
          </Link>
        ))}
        <Outlet />
      </Spin>
    </div>
  );
}

export function Detail() {
  let navigate = useNavigate();
  let { id } = useParams<"id">();
  let image = getImageById(Number(id))!;

  return (
    <Modal open={true} onCancel={() => navigate(-1)} footer={null}>
      <div style={{ padding: "8px 8px" }}>
        <div>{image.title}</div>
        <img
          style={{
            margin: "16px 0",
            borderRadius: "8px",
            width: "100%",
            height: "auto",
          }}
          src={image.src}
          alt=""
        />
      </div>
    </Modal>
  );
}
